package info.tsukaworld.actor;

import info.tsukaworld.actor.Actor;
import info.tsukaworld.actor.Actor;
import info.tsukaworld.grid.*;

public class MovingActor extends Actor
{
    private int tick = 0;
    private int moveSpeed = 40;
    private int currentMove = 0;
    private boolean moving = false;
    private int xOffset;
    private int yOffset;
    
    public MovingActor()
    {
        super();  
        xOffset = 0;
        yOffset = 0;
    }
    
    public MovingActor(String im)
    {
        super(im);
        xOffset = 0;
        yOffset = 0;
    }
    
    public void act()
    {
        tick %= 600;
        if( moving )
        {
            move();
        }
        tick++;
    }
    
    public boolean canMove()
    {
        Grid<Actor> gr = getGrid();
        if (gr == null)
            return false;
        Location loc = getLocation();
        Location next = loc.getAdjacentLocation(getDirection());
        if (!gr.isValid(next))
            return false;
        Actor neighbor = gr.get(next); 
        return (neighbor == null);
    }
    
    public boolean canMove(int direction)
    {
        Grid<Actor> gr = getGrid();
        if (gr == null)
            return false;
        Location loc = getLocation();
        Location next = loc.getAdjacentLocation(direction);
        if (!gr.isValid(next))
            return false;
        Actor neighbor = gr.get(next); 
        return (neighbor == null);
    }
    

    
    public void move()
    {
        moving = true;
        if( currentMove % moveSpeed == 0 && currentMove != 0 )
        {
            moveLocation();
        }
        else
            currentMove++;
    }
    
    public void startMove()
    {
        if( canMove() )
        {
            moving = true;
            //moveLocation();
        }
    }
    
    private void moveLocation()
    {
        currentMove = 0;
        Location target = getLocation().getAdjacentLocation( getDirection() );
        moveTo( target );
        moving = false;
    }
    
    public boolean isMoving()
    {
        return moving;
    }
    
    public int getCurrentMove()
    {
        return currentMove;
    }
    
    public int getMoveSpeed()
    {
        return moveSpeed;
    }
    
    public void turn(int angle)
    {
        if( !moving )
            setDirection(getDirection() + angle);
    }
    
    public void turn()
    {
        if( !moving )
            setDirection(getDirection() + Location.HALF_RIGHT);
    }
    
    public void setMoveSpeed(int newSpeed)
    { moveSpeed = newSpeed; }
    
    public int getXoffset()
    { return xOffset; }
    
    public void setXoffset(int n)
    { xOffset = n; }
    
    public int getYoffset()
    { return yOffset; }
    
    public void setYoffset(int n)
    { yOffset = n; }
}